<?php
/**
 * Created by PhpStorm.
 * User: yxb
 * Date: 2017/1/23
 * Time: 10:27
 */
namespace app\index\controller;
use think\Db;
use think\Controller;
use think\Url;
class Alipay extends Controller{
    /**
     * @param order_id
     * @param order_num
     * @param type 0 id 1 num
     * @param uid
     * @param assess_token
     */

    public function pay($order_id = '',$order_num = '',$order_type = 0,$uid = '',$assess_token = '',$pswd=''){
       
        if (is_token($uid, $assess_token) == 0) {
            return format_return(0, '', "验证错误，请重新登录", 1);
        } else {
            $member = Db::name("members")->where('uid',$uid)->find();
            if($order_type == 0){
                //order_id
                empty($order_id) && $this->error("非法参数");
                $join = [
                    ['goods g', 'g.id=o.g_id', 'left']
                ];
                $field = [
                    'o.order_id',
                    'o.price',
                    'o.order_num',
                    'g.subject',
                    'o.integral',
                    'g.introduction',
                    'g.status',
                    'o.nums',
                    'g.num'
                   
                ];
                $order = Db::name("orders")->alias("o")->where("order_id", $order_id)->join($join)->field($field)->find();
                if($order['status'] == 0){
                    return format_return(0,'','支付失败，商品已下架');
                }
              
                if($order['num'] < $order['nums']){
                    return format_return(0,'','库存不足');
                }
                
                // 异步通知地址
                $notify_url = urlencode('http://www.tianjunhai.com/index/pay/alipay_notify');
                // 订单标题
                $subject = $order['subject'];
                // 订单详情
                $body = $order['introduction'];
                // 订单号，示例代码使用时间值作为唯一的订单ID号
                $out_trade_no = $order_id;
                $total = $order['price'];
                $integral = $order['integral'];
            }else{
                //order_num
                empty($order_num) && $this->error("非法参数");
                $join = [
                    ['goods g', 'g.id=o.g_id', 'left']
                ];
                $field = [
                    'o.order_id',
                    'o.price',
                    'o.order_num',
                    'g.subject',
                    'o.integral',
                    'g.introduction',
                    'g.status',
                    'o.nums',
                    'g.num'
                ];
                $orders = Db::name("orders")->alias("o")->where("order_num", $order_num)->join($join)->field($field)->select();
                $body = '';
                $subject = '';
                // 订单号，示例代码使用时间值作为唯一的订单ID号
                $out_trade_no = $order_num;
                foreach($orders as $key => $value){
                    if($value['status'] == 0){
                        return format_return(0,'','支付失败，商品已下架');
                    }
                    
                    if($value['num'] < $value['nums']){
                        return format_return(0,'','库存不足');
                    }
                    
                    // 订单详情
                    $body .= $value['introduction'];
                    // 订单标题
                    $subject .= $value['subject'];
                }
                $total = array_sum(array_column($orders,'price'));
                // 异步通知地址
                $notify_url = urlencode('http://www.tianjunhai.com/index/pay/alipay_notify_num');
                $integral = array_sum(array_column($orders,'integral'));
            }
            // 支付宝合作者身份ID，以2088开头的16位纯数字
            $partner = "2088021878456483";
            // 支付宝账号
            $seller_id = '370562505@qq.com';
            // 商品网址
            $base_path = urlencode('http://www.tianjunhai.com');
            
            
            if($member['integral'] < $integral){
                return format_return(0, '', "积分不够，支付失败");
            }
            if($total <= $member['balance']){
                if($pswd){
                    $payment = Db::name("pay")->where('uid',$uid)->field('payment')->find();
                    if($payment['payment']!=md5($pswd)){
                        return format_return(0, '', "支付密码错误");
                    }
                 }
                //余额大于价格
                $member['balance'] = $member['balance'] - $total;
                $member['integral'] = $member['integral'] - $integral;
                $data = [
                    'balance'=>$member['balance'],
                    'integral' => $member['integral']
                ];
                Db::name("members")->where('uid',$uid)->update($data);
                if($order_type == 0){
                    $this->back_handle($order_id,'','',0,2);
                    return format_return(0, "1", "余额付款成功");
                }else{
                    $this->back_handle('','',$order_num,1,2);
                    return format_return(0, "1", "余额付款成功");
               
                }
            }else{
               // return format_return(0,'','库存不足');
                //$total = $total - $member['balance'];
                $total=bcsub($total,$member['balance'],2);
               
                $parameter = array(
                    'service'        => 'mobile.securitypay.pay',   // 必填，接口名称，固定值
                    'partner'        => $partner,                   // 必填，合作商户号
                    '_input_charset' => 'UTF-8',                    // 必填，参数编码字符集
                    'out_trade_no'   => $out_trade_no,              // 必填，商户网站唯一订单号
                    'subject'        => $subject,                   // 必填，商品名称
                    'payment_type'   => '1',                        // 必填，支付类型
                    'seller_id'      => $seller_id,                 // 必填，卖家支付宝账号
                    'total_fee'      => $total,                     // 必填，总金额，取值范围为[0.01,100000000.00]
                    'body'           => $body,                      // 必填，商品详情
                    'it_b_pay'       => '1d',                       // 可选，未付款交易的超时时间
                    'notify_url'     => $notify_url,                // 可选，服务器异步通知页面路径
                    'show_url'       => $base_path,                  // 可选，商品展示网站
                    'sign_type'      => 'RSA'
                );
                //生成需要签名的订单
                $orderInfo = $this->createLinkstring($parameter);
                //签名
                $sign = $this->rsaSign($orderInfo);
                //生成订单
                $order_param = $orderInfo.'&sign="'.$sign.'"&sign_type="RSA"';
                return format_return(1,$order_param,"数据获取成功");
            }

        }

    }
    // 对签名字符串转义
    private function createLinkstring($para) {
        $arg  = "";
        while (list ($key, $val) = each ($para)) {
            $arg.=$key.'="'.$val.'"&';
        }
        //去掉最后一个&字符
        $arg = substr($arg,0,count($arg)-2);
        //如果存在转义字符，那么去掉转义
        if(get_magic_quotes_gpc()){$arg = stripslashes($arg);}
        return $arg;
    }
// 签名生成订单信息
    private function rsaSign($data) {
    $priKey = "-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDg5NZ42g9QvqIV03LJZUFm4MLTADV1VrsJx2nSRskVcBud1XHv
sBWWnAD8779PDxJaCzZtQn0AtEKGy8demmczRZrn7mu6yv3WHfsfg5xVOzk+mWDD
N6+fDD+BrfxT1QO6hq/FaBy8p/G6TmGY8RriZgdEPVHCjyfernJ/ZExEJwIDAQAB
AoGAKu6knteJ+vEZgi8mh5nj3V7k8mDk06yl8hz2b6UBuCz5qKzZnlcwF9taOO8P
x2jqKPRhBISf1mWTGaaHPeEd+AkZ/SH4YZ+596dMw+pYF9GTH4CQ8QuFZymr+3ZO
jMjXsjMjdGYM7RNhQunqU0Ak4bGMC0F4cQQ64gBhqJrypbkCQQD2USUIXaR/KXin
4CB5TOKDFLigGjlcqW9DzZ8VIBFQi+AW8luDmaxeLz+y97zx2NrSIPF0uB7Ki9R3
Zs4J+WZVAkEA6bwZIFc6AAvz2f4JwpdEMg5xeigUG5fSNXFkLU/ZByDuCt6NE7DQ
ZkbcrYR6HicgGlciZqJjMllpMbZI4cbki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/gBwfOx7M9U3J8a1vpxPzH408TprtOz4xxGAjZU7D05v6FQUi/g5Z7LhFQaiVfuQXyPDpGDg==";
//        $priKey = "-----BEGIN RSA PRIVATE KEY-----\n" .
//            wordwrap($priKey, 64, "\n", true) .
//            "\n-----END RSA PRIVATE KEY-----";
        $res = openssl_get_privatekey($priKey);
        openssl_sign($data, $sign, $res);
        openssl_free_key($res);
        $sign = base64_encode($sign);
        $sign = urlencode($sign);
        return $sign;
    }

    /**
     * 回调
     * @param order_id 订单id
     * @param order_num 订单num
     * @param type 0 id 1 num 2 balance
     * @param out_trade_no 交易号
     * @param trading_type 0 wx 1 alipay
     */
    public function back_handle($order_id = '', $out_trade_no = '', $order_num = '', $type = 0, $trading_type = 0)
    {
        //order_id
        if ($type == 0) {
            $where = [
                'order_id' => $order_id,
                'status' => 0,
                'is_cancel' => 0,
            ];
            $orders = Db::name('orders')->where($where)->find();
            if (!empty($orders)) {
                $data = [
                    'status' => 1,
                    'trade_no' => $out_trade_no,
                    'trading_type' => $trading_type
                ];
                Db::name('orders')->where($where)->update($data);
                $goods = Db::name("goods")->where('id', $orders['g_id'])->find();
                $update_goods = [
                    'num' => $goods['num']-$orders['nums'],
                    'sell_num' => $goods['sell_num']+$orders['nums']
                ];
                Db::name("goods")->where('id', $orders['g_id'])->update($update_goods);
            }
        } else if ($type == 1){
            //order_num
            $where = [
                'order_num' => $order_num,
                'status' => 0,
                'is_cancel' => 0,
            ];
            $orders = Db::name('orders')->where($where)->select();
            if (!empty($orders)) {
                $data = [
                    'status' => 1,
                    'trade_no' => $out_trade_no,
                    'trading_type' => $trading_type
                ];
                Db::name('orders')->where($where)->update($data);
                $g_ids = array_column($orders,'g_id');
               $where_g = [
                    'g.is_delete' => 0,
                    'g.id' => array('in',$g_ids)
                ];
                 $join = [
                ['goods g', 'g.id=o.g_id', 'left']
                 ];
                 
                $field = [
                 'g.*',  
                'o.nums'
                
                ];
                $goods = Db::name("orders")->alias("o")->where($where_g)->join($join)->field($field)->select();
                foreach($goods as $key => $value){
                    $num=$value['num']-$value['nums'];
                    $sell_num=$value['sell_num']+$value['nums'];
                    $updata = [
                        'num' => $num,
                        'sell_num' => $sell_num
                    ];
                    Db::name("goods")->where('id',$goods[$key]['id'])->update($updata);
                    unset($updata);
                }
            }
        }
    }
}

